package com.ruoyi.framework.config;

import cn.hutool.db.sql.SqlUtil;
import com.github.pagehelper.PageInterceptor;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.framework.flex.CreateByListener;
import com.ruoyi.framework.flex.UpdateByListener;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * Mybatis支持*匹配扫描包
 *
 * @author ruoyi
 */
@Slf4j
@Configuration
@MapperScan("com.ruoyi.**.mapper")
public class MyBatisConfig {

    @Bean
    public PageInterceptor pageInterceptor() {
        return new PageInterceptor();
    }

    @PostConstruct
    public void setFlexConfig() {
//        //开启审计功能
//        AuditManager.setAuditEnable(true);
//        //设置 SQL 审计收集器
//        AuditManager.setMessageCollector(auditMessage -> {
//            String fullSql = auditMessage.getFullSql();
//            if (!fullSql.contains("sys_oper_log")) {
//                log.info("{}ms\n {}", auditMessage.getElapsedTime(), SqlUtil.formatSql(fullSql));
//            }
//        });

        FlexGlobalConfig globalConfig = FlexGlobalConfig.getDefaultConfig();
        // 关闭banner
        globalConfig.setPrintBanner(false);
        //设置数据库正常时的值
        globalConfig.setNormalValueOfLogicDelete("0");
        //设置数据已被删除时的值
        globalConfig.setDeletedValueOfLogicDelete("1");

        CreateByListener defaultInsertListener = new CreateByListener();
        UpdateByListener defaultUpdateListener = new UpdateByListener();
        globalConfig.registerInsertListener(defaultInsertListener, BaseEntity.class);
        globalConfig.registerUpdateListener(defaultUpdateListener, BaseEntity.class);
    }
}
